package com.tarena.demo.luban.all.main.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.tarena.demo.luban.all.main.service.OrderService;
import com.tarena.demo.luban.commons.exception.BusinessDemoException;
import com.tarena.demo.luban.commons.restful.JsonResult;
import com.tarena.demo.luban.protocol.order.param.OrderAddParam;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/base/order")
@Api(tags = "订单")
@Slf4j
public class OrderController {
    /*@Autowired
    private OrderService orderService;*/
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @PostMapping("/add")
    @ApiOperation("新增订单的功能")
    @SentinelResource(
            value="addOrder",
            blockHandler = "addOrderBlock",
            fallback="addOrderError")
    public JsonResult addOrder(OrderAddParam orderAddParam){
        //同步发送 异步发送
        //1. 组织一个包含orderAddParam的消息对象
        Message<OrderAddParam> msg = MessageBuilder.withPayload(orderAddParam).build();
        //2. 调用异步发送asyncSend
        rocketMQTemplate.asyncSend("order-topic", msg, new SendCallback() {
                @Override public void onSuccess(SendResult result) {
                    log.info("发送消息成功:{}",result);
                }
                @Override public void onException(Throwable throwable) {
                    //TODO 调用预警接口 方法 把参数传递 假设设置 每100万条 允许丢失10条以下
                    log.error("发送消息失败",throwable);
                    log.error("消息参数:{},消息主题:{},消息其他内容...",orderAddParam,"order-topic");
                }
            }
        );
        return JsonResult.ok("提交订单完成");
    }
    public JsonResult addOrderBlock(OrderAddParam orderAddParam,BlockException e){
        log.error("下单出现异常",e);
        return JsonResult.ok("下单被拦截住了");
    }
    public JsonResult addOrderError(OrderAddParam orderAddParam,Throwable e){
        log.error("下单出现异常",e);
        return JsonResult.ok("下单逻辑出现业务问题");
    }
}
